#include <stdint.h>
#include "inc/tm4c123gh6pm.h"
#include <stdio.h>
#include <stdlib.h>


void uart_init(void);
void transmitChar(char c);
void adc_init(void);

char c;
char command[10];
char *ptrcmd=&command[0];

int adc_val=0;
int adc_timer=0;
int adc_read_flag=0;

int main(){
    uart_init();
    adc_init();

    while(1)
    {
           adc_read();
           c=(char)(adc_val/16);
           transmitChar(c);

    }
    return 0;

}
void adc_init(){

    // GPIO pin configurations
       SYSCTL_RCGCGPIO_R |= 0x00000010;        // Enable clock at GPIOE (for ADC0)
       SYSCTL_RCGCADC_R |= 0x00000001;         // Enable clock at ADC0 module - bit 0
       GPIO_PORTE_AFSEL_R |= 8;                // Enable alternate function for PORTE bit 3
       GPIO_PORTE_DEN_R &= ~8;                 // Disable digital function for PORTE bit 3
       GPIO_PORTE_AMSEL_R |= 8;                // Enable analog function for PORTE bit 3
       //ADC0_PC_R =7  ; //1msps
       // ADC0 configurations
       // safe practice to disable ADC Sample Sequencer before initializing other registers and then enable again
       // Using Sample Sequencer 3 (One 12-bit Sample FIFO)
       ADC0_ACTSS_R &= ~8;                     // Disable SS3 during configuration
       ADC0_EMUX_R &= ~0x0000F000;             // Software trigger conversion
       ADC0_SSMUX3_R = 0;                      // Enable input from channel 0 (PORTE bit 3)
       ADC0_SSCTL3_R |= 6;                     // Take one sample at a time, set flag at 1st sample
       ADC0_ACTSS_R |= 8;                      // enable ADC0 sequencer 3 Enable SS3
}

void uart_init(void){
    SYSCTL_RCGCUART_R |= (1<<0);   //enable UART0
    SYSCTL_RCGCGPIO_R  |= (1<<0);   //enable corresponding GPIO port

    GPIO_PORTA_AFSEL_R |= (1<<1)|(1<<0); //
    GPIO_PORTA_PCTL_R |=(1<<0)|(1<<4);  // PCTL is 32 bit register, 4 bits are used to select alternate functions of each GPIO pin

    GPIO_PORTA_DEN_R|= (1<<1)|(1<<0);   // GPIO digital enable

    UART0_IBRD_R = 5;/* 16MHz/16=1MHz, 1MHz/104=9600 baud rate */
    UART0_FBRD_R = 0; /* fraction part of baud generator register*/

    UART0_LCRH_R = 0x60; //0110 0000 3->8bit
    UART0_CC_R =0x0;
    UART0_CTL_R=(1<<0)|(1<<8)|(1<<9);

    SYSCTL_RCGC2_R |= 0x00000020; /* enable clock to GPIOF at clock gating control register */

    /*UART INTERRUPT ******/

    UART0_ICR_R =0x010; // Clear receive interrupt
    UART0_IM_R  = 0x0010;
    NVIC_PRI2_R |=  0x00008000;   // priority 4
    NVIC_EN0_R |=0x20;

}

void transmitChar(char data)
{
    while((UART0_FR_R & (1<<5)) != 0); /* wait until Tx buffer not full */
    UART0_DR_R = data;                  /* before giving it another byte */
}

void adc_read(){
    ADC0_PSSI_R |= 8; /* start a conversion sequence 3 */
    while((ADC0_RIS_R & 8) == 0);

    adc_val= ADC0_SSFIFO3_R; /* read conversion result */
    ADC0_ISC_R = 8; /* clear completion flag */

}